package cn.wzc.crystal.platform.i18n.impl;

import cn.wzc.crystal.platform.i18n.I18nProvider;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.lang.NonNull;

import java.text.MessageFormat;
import java.util.Locale;

@Setter
@RequiredArgsConstructor
public class I18nMessageSource extends AbstractMessageSource {

	private final I18nProvider i18nProvider;

	private String defaultLocale;

	@Override
	protected MessageFormat resolveCode(@NonNull String code, Locale locale) {
		String message = i18nProvider.getMessage(code, locale.getLanguage());
		if (StringUtils.isBlank(message)) {
			message = i18nProvider.getMessage(code, defaultLocale);
			if (StringUtils.isBlank(message)) {
				return null;
			}
		}
		return new MessageFormat(message, locale);
	}
}